package org.jsola.hr.web;

import org.apache.commons.io.FilenameUtils;
import org.jsola.common.FileKit;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.EmpSocBackRecordRecordAddDTO;
import org.jsola.hr.dto.EmpSocBackRecordRecordUpdateDTO;
import org.jsola.hr.dto.SocBackRecordImportDTO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.query.EmpSocBackRecordInfoQuery;
import org.jsola.hr.query.EmpSocBackRecordRecordQuery;
import org.jsola.hr.service.IEmpSocBackRecordRecordService;
import org.jsola.hr.vo.EmpSocBackRecordRecordListVO;
import org.jsola.hr.vo.EmpSocBackRecordRecordVO;
import org.jsola.hr.vo.ImportExcelResultListVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;


/**
 * 社保回款记录
 *
 * @author zhr
 */
@RestController("hrEmpSocBackRecordRecordController")
@RequestMapping(HrConstants.API_PATH + "/v1/empSocBackRecordRecords")
public class EmpSocBackRecordRecordController implements IEmpSocBackRecordRecordControllerAPI {

    @Autowired
    private IEmpSocBackRecordRecordService empSocBackRecordRecordService;

    @Override
    @PostMapping
    public Result<EmpSocBackRecordRecordVO> save(@Valid @RequestBody EmpSocBackRecordRecordAddDTO empSocBackRecordRecordAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增社保回款记录权限校验

        return Result.success(
                empSocBackRecordRecordService.save(empSocBackRecordRecordAddDTO, tokenUser)
        );
    }

    @Override
    @PostMapping("/saveBatch")
    public Result<Integer> saveBatch(@RequestBody EmpSocBackRecordRecordAddDTO[] empSocBackRecordRecords) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增社保回款记录权限校验

        return Result.success(
                empSocBackRecordRecordService.saveBatch(empSocBackRecordRecords, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody EmpSocBackRecordRecordUpdateDTO empSocBackRecordRecordUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改社保回款记录权限校验

        int count = empSocBackRecordRecordService.update(empSocBackRecordRecordUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @DeleteMapping(value = "/{empSocBackRecordRecordId}")
    public Result<Integer> delete(@PathVariable String empSocBackRecordRecordId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除社保回款记录权限校验

        int count = empSocBackRecordRecordService.deleteByIds(tokenUser, empSocBackRecordRecordId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] empSocBackRecordRecordIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除社保回款记录权限校验

        int count = empSocBackRecordRecordService.deleteByIds(tokenUser, empSocBackRecordRecordIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{empSocBackRecordRecordId}")
    public Result<EmpSocBackRecordRecordVO> findById(@PathVariable String empSocBackRecordRecordId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看社保回款记录权限校验

        return Result.success(
                empSocBackRecordRecordService.selectById(empSocBackRecordRecordId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<EmpSocBackRecordRecordListVO>> listAll(@Valid EmpSocBackRecordRecordQuery empSocBackRecordRecordQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看社保回款记录权限校验

        return Result.success(
                empSocBackRecordRecordService.select(empSocBackRecordRecordQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<EmpSocBackRecordRecordListVO>> page(@Valid EmpSocBackRecordRecordQuery empSocBackRecordRecordQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empSocBackRecordRecordService.selectPage(empSocBackRecordRecordQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @PostMapping("/importRecord")
    public Result<ImportExcelResultListVO<SocBackRecordImportDTO>> importRecord(@RequestParam("file") MultipartFile file,
                                                                                EmpSocBackRecordInfoQuery query) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        // 临时保存到本地
        String excelFilePath = FileKit.saveFileToLocal(file, null, null, new String[]{"xls", "xlsx"}, null);
        File excelFile = new File(excelFilePath);
        HrException.isTrue(excelFile.exists(), "文件上传失败");
        return Result.success(
                empSocBackRecordRecordService.importRecord(excelFile, query, tokenUser)
        );
    }

    @Override
    @PostMapping("/exportErrorList")
    public ResponseEntity<Resource> exportErrorList(@RequestBody @Valid ImportExcelResultListVO<SocBackRecordImportDTO> errorInfo) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 导出权限校验

        // 导出路径
        String excelFilePath = empSocBackRecordRecordService.errorInfoExport(errorInfo);
        // 编码文件名，防止乱码
        String filenames = new String(FilenameUtils.getName(excelFilePath).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }

}

